/*
 * GuudSurface.cpp
 *
 *  Created on: 2013-1-19
 *      Author: heqiu
 */
#include "GuudSurface.h"

namespace guud {
GuudSurface::GuudSurface() {
	m_pSDL_Surface = NULL;
	m_uiBeginX = 0;
	m_uiBeginY = 0;
	m_uiXpixel = 0;
	m_uiYpixel = 0;
	m_uiXnum = 0;
	m_uiYnum = 0;
	m_bScreen = false;
}
GuudSurface::~GuudSurface() {
	if (m_pSDL_Surface != NULL) {
		if (!m_bScreen) {
			SDL_FreeSurface(m_pSDL_Surface);
		}
		m_pSDL_Surface = NULL;
	}
}
bool GuudSurface::loadImage(const char * pName) {
	SDL_Surface* loadedImage = NULL;
	SDL_Surface* optimizedImage = NULL;
	loadedImage = IMG_Load(pName);
	if (loadedImage != NULL) {
		optimizedImage = SDL_DisplayFormat(loadedImage);
		SDL_FreeSurface(loadedImage);
		if (optimizedImage != NULL) {
			SDL_SetColorKey(optimizedImage, SDL_SRCCOLORKEY,
					SDL_MapRGB(optimizedImage->format, 0, 0xFF, 0xFF));
		}
	}
	m_pSDL_Surface = optimizedImage;
	if (m_pSDL_Surface != NULL) {
		return true;
	} else {
		return false;
	}
}
void GuudSurface::init(uint32_t uiBeginX, uint32_t uiBeginY, uint32_t uiXpixel,
		uint32_t uiYpixel, uint32_t uiXnum, uint32_t uiYnum) {
	m_uiBeginX = uiBeginX;
	m_uiBeginY = uiBeginY;
	m_uiXpixel = uiXpixel;
	m_uiYpixel = uiYpixel;
	m_uiXnum = uiXnum;
	m_uiYnum = uiYnum;
}
bool GuudSurface::createScreen(uint32_t uiWidth, uint32_t uiHeight,
		uint32_t uiBpp) {
	m_pSDL_Surface = SDL_SetVideoMode(uiWidth, uiHeight, uiBpp, SDL_SWSURFACE);
	if (m_pSDL_Surface == NULL) {
		return false;
	}
	m_bScreen = true;
	return true;
}
void GuudSurface::whiteScreen() {
	SDL_FillRect(m_pSDL_Surface, &m_pSDL_Surface->clip_rect,
			SDL_MapRGB(m_pSDL_Surface->format, 0xFF, 0xFF, 0xFF));
}
void GuudSurface::showScreen() {
	SDL_Flip(m_pSDL_Surface);
}
void GuudSurface::setName(const char * pName) {
	SDL_WM_SetCaption(pName, NULL);
}
bool GuudSurface::getRGB(uint32_t uiXpixel, uint32_t uiYpixel,
		uint32_t & color) {
	if (m_pSDL_Surface == NULL) {
		return false;
	}
	if (m_pSDL_Surface->pixels == NULL) {
		return false;
	}
	if ((int) uiXpixel > m_pSDL_Surface->w
			|| (int) uiYpixel > m_pSDL_Surface->h) {
		return false;
	}
	//只支持32位色以上
	if (m_pSDL_Surface->pitch < 4) {
		return false;
	}
	uint32_t uiPos = uiYpixel * m_pSDL_Surface->pitch
			+ uiXpixel * m_pSDL_Surface->format->BytesPerPixel;
	color = *((uint32_t*) ((char *) (m_pSDL_Surface->pixels) + uiPos));
	return true;
}
void GuudSurface::printOut() {
	printf("m_pSDL_Surface->pitch=%d\n", m_pSDL_Surface->pitch);
	printf("m_pSDL_Surface->format->BytesPerPixel=%d\n",
			m_pSDL_Surface->format->BytesPerPixel);
	if (m_pSDL_Surface != NULL) {
		for (uint32_t uj = 0; uj < (uint32_t) m_pSDL_Surface->h; uj++) {
			for (uint32_t ui = 0; ui < (uint32_t) m_pSDL_Surface->w; ui++) {
				uint32_t color = 0;
				bool bFlag = getRGB(ui, uj, color);
				printf("(%d,%d):%d:%u\t", ui, uj, bFlag, color);
			}
			printf("\n");
		}
	}
}
}

